const { createProjectDao, getAllProjectDao, updateProjectDao, getOneProjectDao, deleteProjectDao } = require("../dao/projectDao");
const { formatResponseBody } = require("../utils/tools");
const { validate } = require("validate.js");
const { ValidationError } = require("../utils/errors");

// createProjectService 验证规则
const createProjectServiceRule = {
    name: {
        type: "string",
        presence: {
            allowEmpty: false
        }
    },
    description: {
        type: "string",
        presence: {
            allowEmpty: {
                allowEmpty: false
            }
        }
    },
    url: {
        type: "string",
        presence: {
            allowEmpty: {
                allowEmpty: false
            }
        }
    },
    github: {
        type: "string",
        presence: {
            allowEmpty: {
                allowEmpty: false
            }
        }
    },
    thumb: {
        type: "string",
        presence: {
            allowEmpty: {
                allowEmpty: false
            }
        }
    },
    order: {
        type: "number",
        presence: {
            allowEmpty: {
                allowEmpty: false
            }
        }
    }
}

/**
 * 添加一个项目
 * @param {object} data 
 */
exports.createProjcetService = async (data) => {
    data.description = JSON.stringify(data.description);

    if (validate(data, createProjectServiceRule)) {
        throw new ValidationError("验证失败，数据格式不正确");
    }


    const { dataValues } = await createProjectDao(data);
    return formatResponseBody({ data: dataValues });
}

/**
 * 获取所有项目
 * @returns 
 */
exports.getAllProjectService = async () => {
    const result = await getAllProjectDao();
    for (const item of result) {
        item.description = JSON.parse(item.description);
    }
    return formatResponseBody({ data: result.map(item => item.dataValues) });
}

/**
 * 修改项目
 */
exports.updateProjectService = async (newProject, id) => {
    if (newProject.description) {
        newProject.description = JSON.stringify(newProject.description);
    }

    await updateProjectDao(newProject, id);

    const { dataValues } = await getOneProjectDao(id);
    return formatResponseBody({ data: dataValues });
}


// 删除项目
exports.deleteProjectService = async (id) => {
    const result = await deleteProjectDao(id);
    return formatResponseBody({ data: !!result });
}